import React from 'react';
import { Space, Table, Rate, Form, Modal } from 'antd';
import  { useEffect, useState } from 'react';
import axios from 'axios'

var store = window.localStorage

const request = axios.create({
  baseURL: "http://localhost:8080"
});

var dataSource;

  const CollectionCreateForm = ({ open, onCreate, onCancel }) => {
    const [form] = Form.useForm();
    return (
      <Modal
        open={open}
        title="资料评价"
        okText="确定"
        cancelText="取消"
        onCancel={onCancel}
        // 真正的上传在这里
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              onCreate(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        <Form
          form={form}
          layout="vertical"
          name="form_in_modal"
          initialValues={{
            modifier: 'public',
          }}
        >
          <Form.Item
            name="score"
            rules={[
              {
                required: true,
                message: '打分至少有1星!',
              },
            ]}
          >
            <Rate />
          </Form.Item>
        </Form>
      </Modal>
    );
  };

const Table2 = () => {
  const [open, setOpen] = useState(false);
  const [TableData, setTableData] = useState("")
  const onCreate = (values) => {
    var score_id = store.getItem("ScoreID")
    var user_name = store.getItem("UserName")
    console.log('Received values of form: ', values);
    var score_data = {
      "username": user_name,
      "id": score_id,
      "score": values.score
    }
    console.log(score_data)
    request.post('/api/addScore', score_data).then(  
      res => {  
        console.log(res.data)
        alert("评分成功！")
        window.location.reload()
      }
    ).catch(res => {  // 错误处理
      console.log(res.data.res)
    })
    setOpen(false);
  };
  const columns2 = [
    {
      title: '名称',
      dataIndex: 'title',
      key: 'index',
    },
    {
      title: '上传用户',
      dataIndex: 'uploader',
      key: 'index',
    },
    {
      title: '平均评分',
      dataIndex: 'avg_score',
      key: 'index',
    },
    {
        title: '我的评分',
        dataIndex: 'my_score',
        key: 'index',
    },
    {
        title: '链接',
        key: 'index',
        render: (index) => (
            <Space size="middle">
              <a onClick={() => window.location.href=index.path}>跳转</a>
            </Space>
        ),
    },
    {
        title: '评价',
        key: 'index',
        render: (index) => (
            <Space size="middle">
              <div>
              <a
                    onClick={() => {
                      console.log(index.my_score)
                      if (index.my_score == "") {
                        store.setItem("ScoreID", index.id)
                        setOpen(true);
                      }
                      else {
                        alert("您已经打过分了！")
                      }
                  }}
                >
                评分
                </a>
                <CollectionCreateForm
                    open={open}
                    onCreate={onCreate}
                    onCancel={() => {
                    setOpen(false);
                }}
                />
              </div>
            </Space>
        ),
    }
    ];

    useEffect(()=>{
      const getData = async() => {
        var class_name = store.getItem("ClassPage")
        var user_name = store.getItem("UserName")
        var table_data = {
          "course": class_name,
          "user": user_name
        }
        request.post('/api/getAllUrl', table_data).then(  
          res => {  
            dataSource = res.data
            console.log(res.data)
            let tmp = [...dataSource]
            setTableData(tmp)
          }
        ).catch(res => {  // 错误处理
          console.log(res.data.res)
        })
      }
      getData()
    },[])

    return (
        <Table dataSource={TableData} columns={columns2} />
    )
}

export default Table2